package com.jiuwei.androidbasemodel.network

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Retrofit网络请求管理类
 * 
 * 这是一个单例类，用于创建和管理Retrofit实例，提供统一的网络请求入口
 */
object RetrofitManager {
    
    private const val BASE_URL = "https://api.example.com/" // 替换为实际的API基础URL
    private const val TIMEOUT = 30L // 超时时间，单位秒
    
    /**
     * 创建OkHttpClient实例
     * 配置了日志拦截器、连接超时、读写超时等
     */
    private val okHttpClient: OkHttpClient by lazy {
        val loggingInterceptor = HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        }
        
        OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
            .build()
    }
    
    /**
     * 创建Retrofit实例
     * 配置了基础URL、OkHttpClient和Gson转换器
     */
    private val retrofit: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
    
    /**
     * 创建API服务接口实例
     * @param serviceClass API服务接口类
     * @return API服务接口实例
     */
    fun <T> createService(serviceClass: Class<T>): T {
        return retrofit.create(serviceClass)
    }
    
    /**
     * 重新配置Retrofit实例
     * @param baseUrl 新的基础URL
     * @return 新配置的Retrofit实例
     */
    fun newRetrofit(baseUrl: String): Retrofit {
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
}